package com.joyveb.securitycheck.util;

import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class AESComponent {

	/*
	 * 算法/模式/填充 16字节加密后数据长度 不满16字节加密后长度 AES/CBC/NoPadding 16 不支持
	 * AES/CBC/PKCS5Padding 32 16 AES/CBC/ISO10126Padding 32 16
	 * AES/CFB/NoPadding 16 原始数据长度 AES/CFB/PKCS5Padding 32 16
	 * AES/CFB/ISO10126Padding 32 16 AES/ECB/NoPadding 16 不支持
	 * AES/ECB/PKCS5Padding 32 16 AES/ECB/ISO10126Padding 32 16
	 * AES/OFB/NoPadding 16 原始数据长度 AES/OFB/PKCS5Padding 32 16
	 * AES/OFB/ISO10126Padding 32 16 AES/PCBC/NoPadding 16 不支持
	 * AES/PCBC/PKCS5Padding 32 16 AES/PCBC/ISO10126Padding 32 16
	 */
	private static IvParameterSpec iv = new IvParameterSpec("0123456789ABCDEF".getBytes());
	private static final int KEY_SIZE = 128;
	private static final String transformation = "AES/CBC/PKCS5Padding";

	private AESComponent() {
	}

	public static byte[] genKey() throws NoSuchAlgorithmException {
		KeyGenerator kgen = KeyGenerator.getInstance("AES");
		// kgen.init(KEY_SIZE, new SecureRandom());
		kgen.init(KEY_SIZE);
		SecretKey secretKey = kgen.generateKey();
		byte[] enCodeFormat = secretKey.getEncoded();
		return enCodeFormat;
	}

	public static byte[] encrypt(byte[] data, byte[] key)
			throws NoSuchAlgorithmException, NoSuchPaddingException,
			InvalidKeyException, InvalidAlgorithmParameterException,
			IllegalBlockSizeException, BadPaddingException {
		SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
		Cipher cipher = Cipher.getInstance(transformation);
		cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv);
		return cipher.doFinal(data);
	}

	public static byte[] decrypt(byte[] data, byte[] key)
			throws NoSuchAlgorithmException, NoSuchPaddingException,
			InvalidKeyException, InvalidAlgorithmParameterException,
			IllegalBlockSizeException, BadPaddingException {
		SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
		Cipher cipher = Cipher.getInstance(transformation);
		cipher.init(Cipher.DECRYPT_MODE, keySpec, iv);
		return cipher.doFinal(data);
	}

}
